/**
 * 倒计时
 * Author: Randy
 */
!(function(window,$) {
  var countdowns = [],timerId = 0,frameRate = 100,touchTime=0;

  function render(){
    stopCountdown(timerId);
    timerId = setInterval(function(){ 
      for(var i in countdowns){
        c = countdowns[i];
        if(c.delta >= 0){
          c.dayNode.text(parseInt(c.delta/1000/60/60/24,10).toString().replace(/^(\d)$/,'0$1'));
          c.hourNode.text(parseInt(c.delta/1000/60/60%24,10).toString().replace(/^(\d)$/,'0$1'));
          c.minuteNode.text(parseInt(c.delta/1000/60%60,10).toString().replace(/^(\d)$/,'0$1'));
          c.secondNode.text(parseInt(c.delta/1000%60,10).toString().replace(/^(\d)$/,'0$1'));
          c.delta -= frameRate; 
        }else{
          countdowns.splice(countdowns.indexOf(c),1);
          !countdowns.length && stopCountdown();
        }
      }
    },frameRate);
  }
  $(window).on('touchstart', function(e) {stopCountdown();touchTime=Date.now()});
  $(window).on('touchend', function(e) {
      for(var i in countdowns){
        countdowns[i].delta -= Date.now()- touchTime;
      }
      render();
  });

  window.startCountdown = function($el,start,end){
    countdowns.push({
      dayNode:$el.find('.day-node'),
      hourNode:$el.find('.hour-node'),
      minuteNode:$el.find('.minute-node'),
      secondNode:$el.find('.second-node'),
      end:end,
      delta:Date.parse(end) - Date.parse(start)
    });
    render();
  }
  window.stopCountdown = function(){clearInterval(timerId);}
})(window,$); 